<template>
  <div>
    <el-descriptions>
      <el-descriptions-item width="50%" label="项目名称">{{ isNullOrEmpty( projectName ) }}</el-descriptions-item>
      <el-descriptions-item width="50%" label="所属单位">{{ isNullOrEmpty( unityName ) }}</el-descriptions-item>
      < </el-descriptions>
        <div>
          <el-button v-auth="'system.project-empower.create'" type="primary" :icon="Plus" @click="add">授权监管单位</el-button>
        </div>
        <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
          @selection-change="selectionChange" :isShowPag="false">
          <template #roleNames="{ row }">
            <div >
              <el-tag v-for="(item,index) in row.roleNames " type="success" class="mr-2 flex" >
                {{ isNullOrEmpty(item.roleName) }}
              </el-tag>
            </div>
            
          </template>
          <template #action="{ row }">
            <el-space>
              <sj-link custom-type="sblue" :underline="false" @click="edit(row)" v-auth="'system.project-empower.update'">编辑</sj-link>
              <sj-link custom-type="sred" :underline="false" @click="deletes(row)" v-auth="'system.project-empower.remove'">删除</sj-link>
            </el-space>
          </template>
        </pure-table>
        <div class="mt-5">
          <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
            :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
        </div>
        <!-- </RePage> -->
  </div>
</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'

import editForm from "./form.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus,  } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getunityinfo } from '@/api/manage/Individual-management/regulatory-authorization/index';
import { getList, getInfo, addInfo, editInfo, deleteInfo } from '@/api/manage/projectManagementes/supervise/intex';
import { titles, defaultSearchFrom, defaultInfoFrom } from './index';
import { addDialog } from "@/components/ReDialog";
import { deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customPromiseDebounce } from "@/utils/functions";

import type { infoType } from '@/api/manage/projectManagementes/supervise/intex';
type FormProps = {
  formInline: infoType,
  isLoading: boolean
}

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({} as infoType),
  isLoading: false
});
// console.log("监管授权", props);
const projectName = ref()
const unityName
  = ref()
const searchFrom = ref(defaultSearchFrom());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0,
});

const searchFormRules = [
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const selectionData = ref([]);
const roleTableConfig = [
  // { type: "selection", align: "left" },

  { prop: 'id', label: titles.id, width:  100, fixed: 'left' },
  { prop: 'supUnityName', label: titles.supUnityName, minWidth: 150 },
  { slot: 'roleNames', label: titles.roleNames, minWidth: 150 },
  { prop: 'updatedBy', label: titles.updatedBy, minWidth: 150 },
  { prop: 'updatedAt', label: titles.updatedAt, minWidth: 150 },
  { slot: 'action', label: titles.action, width: 100, fixed: 'right' },
];
onMounted(() => {
  getTableList()
  getTunity()
});
// 获取列表数据
const getTableList = () => {
  searchFrom.value.projectId = props.formInline.id + ''
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
      console.log("ss", tableData.data);

    }
  })
}
//项目监管授权信息
const getTunity = () => {
  getunityinfo({ projectId: props.formInline.id }).then(res => {
    if (res.code === 200) {
      projectName.value = res.result.projectName
      unityName.value = res.result.unityName

      console.log("项目监管授权信息", res);

    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchFrom.value, defaultSearchFrom())
  key.value++
  getTableList()
}
// 详情

// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog()
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑项目授权监管单位", row)
}
// 删除
const deletes = (row?: any) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加项目授权监管单位", row?: any) => {
  console.log("props.formInline.id",props.formInline.id);
  
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      console.log("row", row);
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoFrom(),
          projectName: projectName.value,
          unityName: unityName.value,
          projectId: props.formInline.id
        }
        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {
            showInfo.value = res.result
            options.props.formInline = res.result
            console.log("项目授权监管单位编辑", options.props.formInline);

          }
        }).finally(() => {
          options.props.isLoading = false
        })
      } else {

        options.props = {
          isLoading: false,
          formInline: defaultInfoFrom(),
          projectName: projectName.value,
          unityName: unityName.value,
          projectId: props.formInline.id
        }
        console.log("项目授权监管单位新增", options.props);
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.projectId = props.formInline.id
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加项目授权监管单位") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            console.log("1234");
            
              DebounceEditInfo(formData).then(res => {
                if (res.code == 200) {
                  console.log("1234567");
                  chores();
                }
                options.props.isLoading = false;
              }).catch((err) => {
                console.log("1234567890");
                if (err !== '请求中') {
                  options.props.isLoading = false;
                }
              })
          }
        }
      });
    }
  });
}
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped></style>
